import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/bill/api.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/index.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:dio/dio.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:photo_view/photo_view.dart";
import "package:photo_view/photo_view_gallery.dart";

class BillCollecting extends StatefulWidget {
  final Map info;
  const BillCollecting({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _BillCollectingState();
}

class _BillCollectingState extends State<BillCollecting> {
  late ImagePicker _imagePicker;
  Map _info = {};
  Map<String, dynamic> _params = {
    "billId": null,
    "picUrl": "",
    "remark": "",
    "status": 2
  };
  List<XFile> _selectedImages = [];
  final int _maxImages = 3;
  List<String> _picUrl = [];

  void _updateBill() async {
    if (_selectedImages.isEmpty) {
      EasyLoading.showToast('请选择凭证图片');
      return;
    }

    try {
      EasyLoading.show(status: '正在上传...');
      for (var image in _selectedImages) {
        await _uploadImage(image);
      }
      _params["picUrl"] = _picUrl.join(",");
      await billApi.updateBill(_params);
      EasyLoading.showToast("收款完成");
      if (context.mounted) {
        Navigator.pop(context, true);
      }
    } catch (e) {
      EasyLoading.showError(e.toString());
    } finally {
      EasyLoading.dismiss();
    }
  }

  void _openImagePreview(List<XFile> images, int initialIndex) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          body: Stack(
            children: [
              GestureDetector(
                onTap: () => Navigator.pop(context),
                child: PhotoViewGallery.builder(
                  scrollPhysics: const BouncingScrollPhysics(),
                  builder: (BuildContext context, int index) {
                    return PhotoViewGalleryPageOptions(
                      imageProvider: FileImage(File(images[index].path)),
                      initialScale: PhotoViewComputedScale.contained,
                      minScale: PhotoViewComputedScale.contained,
                      maxScale: PhotoViewComputedScale.covered * 2,
                    );
                  },
                  itemCount: images.length,
                  pageController: PageController(initialPage: initialIndex),
                  backgroundDecoration: const BoxDecoration(
                    color: Colors.black,
                  ),
                ),
              ),
              Positioned(
                top: 40,
                right: 20,
                child: IconButton(
                  icon: const Icon(Icons.close, color: Colors.white),
                  onPressed: () => Navigator.pop(context),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _renderPics() {
    return Wrap(
      spacing: 10,
      runSpacing: 10,
      children: [
        ..._selectedImages.map((image) => Stack(
          children: [
            GestureDetector(
              onTap: () => _openImagePreview(_selectedImages, _selectedImages.indexOf(image)),
              child: Image.file(
                File(image.path),
                width: 100,
                height: 100,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    width: 100,
                    height: 100,
                    color: ThemeVars.colorBackground,
                    child: const Icon(Icons.broken_image),
                  );
                },
              ),
            ),
            Positioned(
              right: 0,
              top: 0,
              child: GestureDetector(
                onTap: () {
                  setState(() {
                    _selectedImages.remove(image);
                  });
                },
                child: Container(
                  padding: const EdgeInsets.all(4),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    borderRadius: const BorderRadius.only(
                      bottomLeft: Radius.circular(4),
                    ),
                  ),
                  child: const Icon(
                    Icons.close,
                    size: 16,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ],
        )),
        if (_selectedImages.length < _maxImages)
          GestureDetector(
            onTap: _pickImage,
            child: Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                color: ThemeVars.colorBackground,
                border: Border.all(color: ThemeVars.colorBorder),
                borderRadius: BorderRadius.circular(4),
              ),
              child: const Icon(Icons.add, size: 40),
            ),
          ),
      ],
    );
  }

  Future<void> _pickImage() async {
    final List<XFile> pickedImages = await _imagePicker.pickMultiImage() ?? [];
    
    if (pickedImages.isNotEmpty) {
      final int remainingSlots = _maxImages - _selectedImages.length;
      
      if (pickedImages.length > remainingSlots) {
        EasyLoading.showToast('最多只能选择${_maxImages}张图片');
        setState(() {
          _selectedImages.addAll(pickedImages.take(remainingSlots));
        });
      } else {
        setState(() {
          _selectedImages.addAll(pickedImages);
        });
      }
    }
  }

  // 图片上传
  Future<void> _uploadImage(XFile? image) async {
    if (image != null) {
      FormData formData = FormData();
      formData.files.add(MapEntry("file", await MultipartFile.fromFile(image.path, filename: image.name)));
      Map res = await commonApi.upload(formData);
      setState(() {
        _picUrl.add(res["data"]["url"]);
      });
      print("图片信息：$res");
    }
  }

  @override
  void didChangeDependencies() {
    setState(() {
      _info = widget.info;
      _params["billId"] = _info["billId"];
    });
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
    _imagePicker = ImagePicker();
  }
  
  @override
  Widget build(BuildContext context) {
    return NormalScaffold(
      title: "完成收款",
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          MenuBlock(
            borderRadius: const BorderRadius.all(Radius.circular(0)),
            items: [
              MenuBlockItem(
                text: "费用名称",
                showArrow: false,
                suffix: Text(_info["name"]),
              ),
              MenuBlockItem(
                text: "账单金额",
                showArrow: false,
                suffix: Text(_info["money"].toStringAsFixed(2)),
              ),
              MenuBlockItem(
                text: "待收日期",
                showArrow: false,
                suffix: Text(DateTools.formatYMD(_info["noticeDate"])),
              ),
              MenuBlockItem(
                text: "添加员工",
                showArrow: false,
                suffix: Text(_info["receiverName"]),
              ),
              MenuBlockItem(
                text: "账单备注",
                suffix: Text(Utils.isNotEmpty(_params["remark"])  ? "已填写" : "请填写"),
                onTap: () {
                  Stacker.pushNamed(Keys.APARTMENT_EDIT_REMARK, arguments: _params["remark"])
                    .then((value) {
                      if (value != null) {
                        setState(() {
                          _params["remark"] = value;
                        });
                      }
                    });
                  // Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                  //   return EditRemark(remark: _params["remark"]);
                  // })).then((value) {
                  //   if (value != null) {
                  //     setState(() {
                  //       _params["remark"] = value;
                  //     });
                  //   }
                  // });
                }
              ),
              MenuBlockItem(
                text: "凭证图片",
                showArrow: false,
                tip: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _renderPics(),
                    const SizedBox(height: 8),
                    const Text(
                      "仅限3张图片，单张图片不超过10M，仅支持PNG/JPG格式",
                      style: TextStyle(
                        color: ThemeVars.colorTextTer,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(ThemeVars.paddingPage, 30, ThemeVars.paddingPage, 30),
            child: Button(
              type: ButtonType.primary,
              onPressed: () {
                _updateBill();
              },
              child: const Text("完成收款"),
            ),
          )
        ],
      ),
    );
  }

}